package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.entityVo.userDemoVo;
import com.antdesignbackend.backend.entity.userDemo;
import com.antdesignbackend.backend.service.UserDemoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/list")
@SuppressWarnings("unchecked")
public class UserDemoController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserDemoService userDemoService;
    //也可以直接注入mapper来进行操作
    // @Autowired
    //userDemoMapper userDemoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询全部
     *
     * @param message
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/selectList")
    public ReturnVO selectList(@RequestParam(value = "msg") String message) {
        redisTemplate.opsForValue().set("name", "luyangjia");
        Map<String, String> cookiesMap = new HashMap<>();
        cookiesMap.put("verifyCode", "27af3dffe24cae66179a88d231f2dfa471987d72");
        cookiesMap.put("c", "bc70ba6e50f44503bc02e963d583df07");
        cookiesMap.put("collect_id", "pskrkbfrj5i389kjq6pdxuq2n81tnqtf");
        cookiesMap.put("channel", "0705");
        cookiesMap.put("ssoFailFlag", "1");
        cookiesMap.put("rdmdmd5", "A47B8B40A725A8C2005FDD7EF3B8193B");
        cookiesMap.put("cmccssotoken", "bc70ba6e50f44503bc02e963d583df07@.10086.cn");

        redisTemplate.opsForHash().putAll("18695611805", cookiesMap);
//        redisTemplate.opsForHash().entries("18695611805");
//        redisTemplate.opsForHash().values("18695611805");
//        redisTemplate.opsForHash().keys("18695611805");
//        (String)redisTemplate.opsForHash().get("18695611805","telephone");
        List<userDemo> userDemos = userDemoService.getBaseMapper().selectList(null);
//        userDemoService.list();这种写法是标准写法功能跟上一句一样，userDemoService.getBaseMapper()是访问父类接口来进行调用
        logger.info("succ");
//        return JSON.toJSONString(userDemos);
        return new ReturnVO(userDemos);
    }

    /**
     * <p>
     * 根据 Wrapper 条件，查询全部记录
     * </p>
     *
     * @param queryWrapper 实体对象封装操作类（可以为 null）
     */
    @ResponseBody
    @GetMapping(value = "/selectMaps")
    public void selectMaps() {
        QueryWrapper<userDemo> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("name");
        List<Map<String, Object>> maps = userDemoService.getBaseMapper().selectMaps(queryWrapper);
        for (Map<String, Object> map : maps) {
            System.out.println(map);
        }
    }

    /**
     * <p>
     * 根据根据 entity 条件，删除记录,QueryWrapper实体对象封装操作类（可以为 null）
     * 下方获取到queryWrapper后删除的查询条件为name字段为null的and年龄大于等于12的and email字段不为null的
     * 同理写法条件添加的方式就不做过多介绍了。
     * </p>
     */
    @ResponseBody
    @GetMapping(value = "/delete")
    public void delete() {
        QueryWrapper<userDemo> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .isNull("name")
                .ge("age", 18)
                .isNotNull("email");
        int delete = userDemoService.getBaseMapper().delete(queryWrapper);
        System.out.println("delete return count = " + delete);
    }

    /**
     * <p>
     * 根据 entity 条件，查询一条记录,
     * 这里和上方删除构造条件一样，只是seletOne返回的是一条实体记录，当出现多条时会报错
     * </p>
     */
    @ResponseBody
    @GetMapping(value = "/selectOne")
    public void selectOne() {
        QueryWrapper<userDemo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "Jack");

        userDemo user = userDemoService.getBaseMapper().selectOne(queryWrapper);
        System.out.println(user);
    }

    /**
     * <p>
     * 根据 Wrapper 条件，查询总记录数
     * </p>
     *
     * @param queryWrapper 实体对象
     */
    @ResponseBody
    @GetMapping(value = "/selectCount")
    public void selectCount() {
        QueryWrapper<userDemo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "lqf");

        Integer count = userDemoService.getBaseMapper().selectCount(queryWrapper);
        System.out.println(count);
    }

    /**
     * <p>
     * 根据 entity 条件，查询全部记录（并翻页）
     * </p>
     *
     * @param page         分页查询条件（可以为 RowBounds.DEFAULT）
     * @param queryWrapper 实体对象封装操作类（可以为 null）
     */
    @ResponseBody
    @GetMapping(value = "/selectPage")
    public void selectPage() {
        Page<userDemo> page = new Page<>(1, 3);
        QueryWrapper<userDemo> queryWrapper = new QueryWrapper<>();

        IPage<userDemo> userIPage = userDemoService.getBaseMapper().selectPage(page, queryWrapper);
        System.out.println(userIPage);
    }

    /**
     * 打印结果
     * ==>  Preparing: SELECT COUNT(1) FROM user
     * ==> Parameters:
     * <==    Columns: COUNT(1)
     * <==        Row: 100
     * ==>  Preparing: SELECT id,name,age,email,status FROM user LIMIT 0,5
     * ==> Parameters:
     * <==    Columns: id, name, age, email, status
     * <==        Row: 1046282328366391319, lqf, 12, lqf@163.com, 0
     * <==        Row: 1046282328366391320, lqf, 12, lqf@163.com, 0
     * <==        Row: 1046282328366391321, lqf, 12, lqf@163.com, 0
     * <==        Row: 1046282328366391322, lqf, 12, lqf@163.com, 0
     * <==        Row: 1046282328366391323, lqf, 12, lqf@163.com, 0
     * <==      Total: 5
     */

    @ResponseBody
    @GetMapping(value = "/update")
    public void update() {

        //修改值
        userDemo user = new userDemo();
        user.setName("zhangsan");

        //修改条件s
        UpdateWrapper<userDemo> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("name", "lqf");

        int update = userDemoService.getBaseMapper().update(user, userUpdateWrapper);

        System.out.println(update);
    }
    /**
     * 打印结果
     * ==>  Preparing: UPDATE user SET name=? WHERE name = ?
     * ==> Parameters: zhangsan(String), true(Boolean), lqf(String)
     * <==    Updates: 100
     * Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@56a4f272]
     * 100
     * INFO 7972 --- [       Thread-2] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@37313c65: startup date [Tue Oct 02 15:08:00 CST 2018]; root of context hierarchy
     * INFO 7972 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
     * INFO 7972 --- [       Thread-2] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
     *
     * Process finished with exit code 0
     */

    /**
     * ***********************************************
     * ***********************************************
     * xml配置到方式查询、更新、插入、删除
     * ***********************************************
     * ***********************************************
     */

    /**
     * xml配置到方式查询
     */
    @ResponseBody
    @GetMapping(value = "/my_selectAllUsers")
    public void my_selectAllUsers() {
        userDemoService.selectUserDemo(new QueryWrapper<userDemo>().eq("name", "Jack"));
    }

    /**
     * xml配置到方式更新
     */
    @ResponseBody
    @GetMapping(value = "/upateuserDemo")
    public void upateuserDemo() {
        userDemoService.updateUsers(new UpdateWrapper<userDemo>().set("name", "Tom1").set("age", "28").eq("id", 3).eq("age", "30"));
    }

    /**
     * xml配置到方式插入
     */
    @ResponseBody
    @GetMapping(value = "/insertuserDemo")
    public void insertuserDemo() {
        userDemo userDemo = new userDemo();
        userDemo.setId(6);
        userDemo.setName("yy");
        userDemo.setAge(31);
        userDemo.setEmail("100238904@qq.com");
        userDemoService.insertUser(userDemo);
    }

    /**
     * xml配置到方式删除
     */
    @ResponseBody
    @GetMapping(value = "/deleteuserDemo")
    public void deleteuserDemo() {
        userDemo userDemo = new userDemo();
        userDemo.setId(6);
        userDemoService.delUserById(6);
    }


    /**
     * ***********************************************
     * ***********************************************
     * xml配置多表关联查询及多表关联查询分页
     * ***********************************************
     * ***********************************************
     */
    @ResponseBody
    @GetMapping(value = "/selectuserDemoVo")
    public ReturnVO selectuserDemoVo() {
        List<userDemoVo> userDemoVos = userDemoService.selectuserDemoVo(
                new QueryWrapper<userDemoVo>().eq("name", "Jack").or().eq("name", "Jone"));
        System.out.println();
        return new ReturnVO(userDemoVos);
    }

    @ResponseBody
    @GetMapping(value = "/selectuserDemoVoPage")
    public ReturnVO selectuserDemoVoPage() {
        List<userDemoVo> userDemoVos = userDemoService.selectuserDemoVoPage(
                new QueryWrapper<userDemoVo>().eq("name", "Jack").or().eq("name", "Jone"), new Page<>(1, 1));
        System.out.println();
        return new ReturnVO(userDemoVos);
    }
}
